<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>canvas</title>
  <style>
    html,
    body {
      margin: 0;
    }

    canvas {
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="500" height="320">
    你的浏览器太low了~
  </canvas>
  <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas')
      if (canvas.getContext) {
        // canvas动画原理
        // 1、绘制图像
        // 2、清除图像
        // 3、移动位置
        // 4、绘制图像
        // 5、2 3 4 2 3 4
        var ctx = canvas.getContext('2d')


        var x = 0;
        var y = 0;
        var w = 50;
        var h = 50;
        ctx.fillStyle = 'pink';
        ctx.fillRect(x, y, w, h);

        var speedx = 2;
        var speedy = 2;

        var t = setInterval(() => {
          ctx.clearRect(x, y, w, h); // 清楚上次矩形：ctx.clearRect(0, 0, canvas.width, canvas.height);两种都ok
          x += speedx;
          y += speedy;

          if (x > canvas.width - w || x < 0) {// 边界判断
            speedx *= -1;
          }
          if (y > canvas.height - h || y < 0) {// 边界判断
            speedy *= -1;
          }
          ctx.fillRect(x, y, w, h);
        }, 10);


      } else {
        alert('你的浏览器太low了~')
      }
    }
  </script>

</body>

</html>